package cn.com.server.dict;

import cn.com.common.RegistryInfo;
import cn.com.registry.Notify;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 监听
 *
 * @param <T>
 * @author jiaming
 */
public class AppDictionary<T> implements Notify {

    protected static final Logger log = LogManager.getLogger();

    private static final Map<String, Set<RegistryInfo>> appMap = new ConcurrentHashMap<>();

    @Override
    public void notify(List<? extends RegistryInfo> putRegInfos, List<? extends RegistryInfo> delRegInfos) {
        if ((putRegInfos == null || putRegInfos.isEmpty())
                && (delRegInfos == null || delRegInfos.isEmpty())) {
            return;
        }
        if (!delRegInfos.isEmpty()) {
            for (RegistryInfo delRegInfo : delRegInfos) {
                log.info("客户端下线，RegistryInfo：{}", delRegInfo.toString());
                Set<RegistryInfo> registryInfoSet = appMap.get(delRegInfo.getAppName());
                if (registryInfoSet.contains(delRegInfo)) {
                    registryInfoSet.remove(delRegInfo);
                }
            }
        }
        if (!putRegInfos.isEmpty()) {
            for (RegistryInfo putRegInfo : putRegInfos) {
                log.info("新增客户端，RegistryInfo：{}", putRegInfo.toString());
                Set<RegistryInfo> set = appMap.get(putRegInfo.getAppName());
                if (set == null) {
                    set = new HashSet<>();
                    set.add(putRegInfo);
                    appMap.put(putRegInfo.getAppName(), set);
                } else {
                    if (!set.contains(putRegInfo)) {
                        set.add(putRegInfo);
                    }
                }
            }
        }
    }

    /**
     * 根据appName获取需要推送hotkey的client
     *
     * @param appName
     * @return
     */
    public static Set<RegistryInfo> getAppRegistryInfo(String appName) {
        return appMap.get(appName);
    }

}